<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="800">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="140px"
      v-loading="formLoading"
    >
      <el-row :gutter="20">
        <el-col :span="16">
          <el-form-item label="客户名称" prop="customerId">
            <el-select
              v-model="formData.customerId"
              :disabled="formData.customerDefault"
              class="w-1/1"
              filterable
              placeholder="请选择客户"
            >
              <el-option
                v-for="item in customerList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="16">
          <el-form-item label="房产" prop="houseSkuId">
            <el-select
              v-model="formData.houseSkuId"
              :disabled="formData.houseSkuDefault"
              class="w-1/1"
              filterable
              placeholder="请选择房产"
              @change="handleHouseSkuChange(formData.houseSkuId)"
            >
              <el-option
                v-for="item in houseSkuList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="是否使用新面积" prop="useNewArea">
            <el-radio-group v-model="formData.useNewArea">
              <el-radio
                v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
                :key="dict.value"
                :label="dict.value"
              >
                {{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>


    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import * as CustomerApi from '@/api/crm/customer'
import * as HouseSpuApi from '@/api/house/house/spu'
import { getBoolDictOptions, DICT_TYPE } from '@/utils/dict'

/** CRM 运营信息 表单 */
defineOptions({ name: 'HouseSkuForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const customerList = ref([]) // 客户列表的数据
const houseSkuList = ref([]) // 房产列表的数据
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  customerId: undefined,
  customerDefault: false,
  houseSkuId: undefined,
  houseSkuDefault: false,
  useNewArea: undefined,
})
const formRules = reactive({
  customerId: [{ required: true, message: '客户不能为空', trigger: 'blur' }],
  houseSkuId: [{ required: true, message: '房产不能为空', trigger: 'blur' }],
  useNewArea: [{ required: true, message: '是否使用新面积不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number, customerId?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  if (id || customerId) {
    formLoading.value = true
    try {
      // 修改时，设置数据
      if(id){
        const data = await HouseSpuApi.getSku(id)
        formData.value = data
        formData.value.houseSkuId = id
        formData.value.houseSkuDefault = true
        formData.value.customerDefault = true // 默认客户的选择，不允许变
      }else{
        formData.value.customerId = customerId
        formData.value.customerDefault = true // 默认客户的选择，不允许变
      }
    } finally {
      formLoading.value = false
    }
  }
  // 获得客户列表
  customerList.value = await CustomerApi.getCustomerSimpleList()
  // 获得房产sku列表
  houseSkuList.value = await HouseSpuApi.getHouseSkuSimpleList()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as HouseSpuApi.Sku
    if (formType.value === 'create') {
      await HouseSpuApi.updateSku(data)
      message.success(t('common.createSuccess'))
    } else {
      await HouseSpuApi.updateSku(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const handleHouseSkuChange = async (houseSkuId: number) => {
  const houseSku = houseSkuList.value.find<HouseSpuApi.Sku>((item) => item.id === houseSkuId)
    if (houseSku) {
      formData.value.id = houseSku.id
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    customerId: undefined,
    customerDefault: false,
    houseSkuId: undefined,
  },
  formRef.value?.resetFields()
}
</script>